# 需求：通过登录 进入网页主页面

#
# __VIEWSTATE: U0l8UoPhakzb/iO9B3mM+gY/xx8sx6L6UguZoNy8R2DV5SaeTApEFqWGI0nH4ZkRSLhAbJelGUjSgHDHh9u2MdRHyR/8FX3lIknCJju7MO/SZcoTT7sm7iNRwUVLi5KIpO+Xy9Uql4Z75fSlPJr82X+6dAU=
# __VIEWSTATEGENERATOR: C93BE1AE
# from: http://www.gushiwen.cn/user/collect.aspx
# email: 1626467682@qq.com
# pwd: VmJN.fJiku8L5j
# code: 6sln
# denglu: 登录

# 难点：
#   1.__VIEWSTATE __VIEWSTATEGENERATOR  # Anti CSRF Token（可以理解为一个放置CSRF攻击的一个随机刷新的token）
#   2.验证码

import requests
from bs4 import BeautifulSoup
import urllib.request

from hashlib import md5


class Chaojiying_Client(object):

    def __init__(self, username, password, soft_id):
        self.username = username
        password = password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files,
                          headers=self.headers)
        return r.json()

    def PostPic_base64(self, base64_str, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
            'file_base64': base64_str
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, headers=self.headers)
        return r.json()

    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()


url = 'https://www.gushiwen.cn/user/login.aspx?from=http://www.gushiwen.cn/user/collect.aspx'

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36'
}

response = requests.get(url, headers=headers)
content = response.text

#  解析网页并获取 __VIEWSTATE __VIEWSTATEGENERATOR
soup = BeautifulSoup(content, 'lxml')
__VIEWSTATE = soup.find('input', attrs={'id': '__VIEWSTATE'}).get('value')
__VIEWSTATEGENERATOR = soup.find('input', attrs={'id': '__VIEWSTATEGENERATOR'}).get('value')

# 获取验证码图片
img_url = "https://www.gushiwen.cn" + soup.find('img', attrs={'id': 'imgCode'}).get('src')

# 解析验证码 复制给code
# 但是这种方式获取的code与浏览器获取的code不一样（不是同一个请求）
# urllib.request.urlretrieve(img_url, "code.jpg")
# requests里面有一个方法session（）通过session的返回值就能使用请求变成一个对象
session = requests.session()
# 获取验证码中url的内容
response_code = session.get(img_url)
# 注意此时要使用二进制数据  因为我们要使用的是图片的下载
img_data = response_code.content
# wb的模式就是写入二进制数据
with open("code.jpg", "wb") as f:
    f.write(img_data)

# 超级鹰识别验证码
chaojiying = Chaojiying_Client('mannorrediaz', 'mannorrediaz', '963899')
im = open('code.jpg', 'rb').read()
code_name = chaojiying.PostPic(im, 1902).get("pic_str")

# 构造登录数据
login_url = "https://www.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fwww.gushiwen.cn%2fuser%2fcollect.aspx"
data_post = {
    "__VIEWSTATE": __VIEWSTATE,
    "__VIEWSTATEGENERATOR": __VIEWSTATEGENERATOR,
    "from": "http://www.gushiwen.cn/user/collect.aspx",
    "email": "1626467682@qq.com",
    "pwd": "VmJN.fJiku8L5j",
    "code": code_name,
    "denglu": "登录"
}

# res = requests.post(login_url, data=data_post, headers=headers)
res = session.post(login_url, data=data_post, headers=headers)  # 使用session发起请求，保证验证码的请求和登录的请求是同一个
content_res = res.text
with open('gushiwen.html', 'w', encoding='utf-8') as f:
    f.write(content_res)
